package cn.gongxi.weibo.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
         * 登录状态校验
         * 1、获取httpsession会话参数
         *    request.getSession().getAttribute("   ")
         * 2、在会话中获取标识：session.getAttribute("user")
         * 3、判断是否为空，为空则拦截 重定向到登录页
         *
         */
        // 获取session
        Object user = request.getSession().getAttribute("user");

        log.debug("user " + user);
        if (user == null) {
            // 未登录，拦截
            log.info("未登录，拦截");
            // 跳转登录页面
            response.sendRedirect("/login.html");
            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
